package cn.edu.hyit.zhao.utils;

import javax.servlet.http.HttpServletRequest;

public class StringUtil extends org.apache.commons.lang3.StringUtils {
	/**
	 * 判断输入的字符串参数是否为空
	 * 
	 * @param args
	 *            输入的字串
	 * @return true/false
	 */
	public static boolean validateNull(String args) {
		if (args == null || args.length() == 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 判断输入的字符串参数是否为空或者是"null"字符， 如果是，则返回target参数 否则就返回source参数
	 */
	public static String changeNull(String source, String target) {
		if (source == null || source.length() == 0
				|| source.equalsIgnoreCase("null")) {
			return target;
		} else {
			return source;
		}
	}

	/**
	 * 过滤<, >,\n 字符的方法
	 * 
	 * @param input
	 *            需要过滤的字符
	 * @return 完成过滤后的字符串
	 */
	public static String filterHtml(String input) {
		if (input == null) {
			return null;
		}
		if (input.length() == 0) {
			return input;
		}
		input = input.replaceAll("&", "&amp;");
		input = input.replaceAll("<", "&lt;");
		input = input.replaceAll(">", "&gt;");
		input = input.replaceAll(" ", "&nbsp;");
		input = input.replaceAll("'", "&#39;");
		input = input.replaceAll("\"", "&quot;");
		return input.replaceAll("\n", "<br>");
	}

	public static String cardMacConvert(String cardid) {
		cardid = cardid.replace("\n", "");
		Long tmp = Long.valueOf(cardid);
		String tmpStr = Long.toHexString(tmp);
		int i = 0;
		if (tmpStr.length() < 8) {
			for (i = 7 - tmpStr.length(); i >= 0; i--)
				tmpStr = "0" + tmpStr;
		}
		char charSquence[] = tmpStr.toCharArray();
		String result = String.valueOf(charSquence[6])
				+ String.valueOf(charSquence[7])
				+ String.valueOf(charSquence[4])
				+ String.valueOf(charSquence[5])
				+ String.valueOf(charSquence[2])
				+ String.valueOf(charSquence[3])
				+ String.valueOf(charSquence[0])
				+ String.valueOf(charSquence[1]);
		Long idcard = Long.parseLong(result, 16);
		result = Long.toString(idcard);
		return result;
	}

	/**
	 * 验证用户的账号只能为id
	 */
	public static boolean validateUserid(String str) {
		String reg = "[1-9][0-9]{4,9}";
		boolean b = str.matches(reg);
		return b;
	}

	/**
	 * 获得用户远程地址
	 */
	public static String getRemoteAddr(HttpServletRequest request) {
		String remoteAddr = request.getHeader("X-Real-IP");
		if (isNotBlank(remoteAddr)) {
			remoteAddr = request.getHeader("X-Forwarded-For");
		} else if (isNotBlank(remoteAddr)) {
			remoteAddr = request.getHeader("Proxy-Client-IP");
		} else if (isNotBlank(remoteAddr)) {
			remoteAddr = request.getHeader("WL-Proxy-Client-IP");
		}
		return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
	}

}
